package xyz.zyt123.hikvideo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import xyz.zyt123.hikvideo.bean.User;
import xyz.zyt123.hikvideo.bean.Video;
import xyz.zyt123.hikvideo.service.VideoService;

import java.io.File;
import java.util.Date;

/**
 * @author zhuyuntao
 */
public class VideoThread extends Thread {
  private static final Logger log = LoggerFactory.getLogger(VideoThread.class);
  private final VideoMgr videoMgr;
  private final VideoService videoService;
  private final User user;
  private final String reason;

  public VideoThread(VideoMgr videoMgr, VideoService videoService, User user, String reason) {
    this.videoMgr = videoMgr;
    this.videoService = videoService;
    this.user = user;
    this.reason = reason;
    super.setDaemon(true);
  }

  @Override
  public void run() {
    int user = videoMgr.loginV40();
    if (user == -1) {
      System.out.println("请先注册");
      return;
    }
    try {
      while (true) {
        try {
          Thread.sleep(1);
        } catch (InterruptedException ex) {
          return;
        }
        video(user);
        log.info("循环执行:{}", new Date());
      }
    } catch (Throwable exception) {
      log.error("录制失败:", exception);
    } finally {
      videoMgr.logout(user);
    }
    CacheUtil.VIDEO_CACHE.remove(videoMgr.getDevice().getId());
  }

  private void video(int id) {
    Date startTime = new Date();
    File video = videoMgr.realPlay(id, 1);
    if (video != null) {
      Video entity = new Video();
      entity.setPath(video.getName());
      entity.setTime(new Date());
      entity.setStartTime(startTime);
      entity.setEndTime(new Date());
      entity.setUserId(user.getId());
      entity.setUserName(user.getNickname());
      entity.setReason(reason);
      entity.setDeviceId(videoMgr.getDevice().getId());
      videoService.save(entity);
    }
  }
}
